package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        // 准备日期列表数据
        List<LocalDate> localDates = getDateList(begin, end);
        // 准备一个存放统计当天营业额的金额
        List<Double> turnoverList = new ArrayList<>();
        localDates.forEach(date -> {
            // 准备营业额数据
            // 查询订单表 状态，已完成 日期，下单时间
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN));
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX));
            Double turnover = ordersMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        });

        // 构造TurnoverReportVO对象
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(localDates, ','))
                .turnoverList(StringUtils.join(turnoverList, ','))
                .build();
    }

    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        // 准备日期列表数据
        List<LocalDate> localDates = getDateList(begin, end);
        // 准备列表用户数据
        List<Integer> userUserList = new ArrayList<>();
        // 查询每日新增用户数量
        localDates.forEach(date -> {
            // 准备营业额数据
            // 查询订单表 状态，已完成 日期，下单时间
            Map map = new HashMap();
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN));
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX));
            Integer users = userMapper.countByMap(map);
            users = users == null ? 0 : users;
            userUserList.add(users);
        });
        // 总用户数量表
        List<Integer> allUserUserList = new ArrayList<>();
        localDates.forEach(date -> {
            // 准备营业额数据
            // 查询订单表 状态，已完成 日期，下单时间
            Map map = new HashMap();
            map.put("beginTime", null);
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX));
            Integer allUsers = userMapper.countByMap(map);
            allUsers = allUsers == null ? 0 : allUsers;
            allUserUserList.add(allUsers);
        });
        //     构造UserReportVO对象
        return UserReportVO.builder()
                .dateList(StringUtils.join(localDates, ','))
                .newUserList(StringUtils.join(userUserList, ','))
                .totalUserList(StringUtils.join(allUserUserList, ','))
                .build();
    }

    /**
     * 订单统计接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        // 准备日期列表数据
        List<LocalDate> dateList = getDateList(begin, end);
        // 每日订单列表
        List<Integer> totalDayOrderList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;
        for (LocalDate date : dateList) {
            // 获取每日订单总数
            Map map = new HashMap();
            map.put("status", null);
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN));
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX));
            Integer totalOrder = ordersMapper.countByMap(map);
            totalDayOrderList.add(totalOrder);
            // 获取每日有效订单总数
            map.put("status", Orders.COMPLETED);
            Integer validOrder = ordersMapper.countByMap(map);
            validOrderCountList.add(validOrder);
            // 获取总订单
            totalOrderCount += totalOrder;
            // 获取总有效订单数
            validOrderCount += validOrder;

        }
        // 获取总完成率
        Double orderCompletionRate = 0.0;
        try {
            orderCompletionRate = (validOrderCount + 0.0) / totalOrderCount;
        } catch (Exception e) {

        }
        // 返回OrderReportVO对象
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ','))
                .orderCountList(StringUtils.join(totalDayOrderList, ','))
                .validOrderCountList(StringUtils.join(validOrderCountList, ','))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        //     收集名字列表
        List<String> nameList = new ArrayList<>();
        List<Object> numberList = new ArrayList<>();

        //     查询
        Map map = new HashMap();
        map.put("status", Orders.COMPLETED);//已完成的
        // 在某段时间内
        map.put("beginTime", LocalDateTime.of(begin, LocalTime.MIN));
        map.put("endTime", LocalDateTime.of(end, LocalTime.MAX));
        List<GoodsSalesDTO> summedTop10 = ordersMapper.sumTop10(map);
        //     收集销量列表
        for (GoodsSalesDTO goodsSalesDTO : summedTop10) {
            nameList.add(goodsSalesDTO.getName());
            numberList.add(goodsSalesDTO.getNumber());
        }
        //     返回SalesTop10ReportVO对象
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ','))
                .numberList(StringUtils.join(numberList, ','))

                .build();
    }

    /**
     * 导出excel表
     *
     * @param response
     */
    @Override
    public void export(HttpServletResponse response) {
        // 1.查询近30天的运营数据
        LocalDate now = LocalDate.now();        // 2024-05-23
        LocalDate end = now.minusDays(1); // 2024-05-22
        LocalDate begin = now.minusDays(30);    // 2024-04-22
        // LocalDateTime end =
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);

        // 2.往Excel表中写入数据
        // 根据类加载器读取项目中的模板文件, 基于模板文件创建Excel对象
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("运营数据报表模板.xlsx");
        try {
            XSSFWorkbook workbook = new XSSFWorkbook(is);
            XSSFSheet sheet = workbook.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue("时间：" + begin + "至" + end);
            sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());    //营业额
            sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());    //订单完成率
            sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());    //新增用户数

            sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount()); //有效订单
            sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());       //平均客单价

            // 30天明细数据填充
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                beginTime = LocalDateTime.of(date, LocalTime.MIN); //4-23 00:00
                endTime = LocalDateTime.of(date, LocalTime.MAX);   //4-23 23:59:59.999999
                businessData = workspaceService.getBusinessData(beginTime, endTime);

                sheet.getRow(7 + i).getCell(1).setCellValue(date.toString());
                sheet.getRow(7 + i).getCell(2).setCellValue(businessData.getTurnover());
                sheet.getRow(7 + i).getCell(3).setCellValue(businessData.getValidOrderCount());
                sheet.getRow(7 + i).getCell(4).setCellValue(businessData.getOrderCompletionRate());
                sheet.getRow(7 + i).getCell(5).setCellValue(businessData.getUnitPrice());
                sheet.getRow(7 + i).getCell(6).setCellValue(businessData.getNewUsers());
            }

            // 3.通过输出流将Excel文件对象下载到客户端浏览器
            ServletOutputStream os = response.getOutputStream();
            workbook.write(os);

            // 4.释放资源
            os.close();
            workbook.close();
            is.close();
        } catch (IOException e) {
            log.error("文件写入失败！！！{}", e.getMessage());
        }
    }


    /**
     * 获取日期列表数据
     *
     * @param begin
     * @param end
     * @return
     */
    //     抽取方法
    private List<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        // 准备日期列表数据
        List<LocalDate> localDates = new ArrayList<>();
        // 循环插入日期数据
        while (!begin.isAfter(end)) {
            localDates.add(begin);
            begin = begin.plusDays(1);
        }
        return localDates;
    }
}
